<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Billboard;
use App\Models\UserBillboard;
use DB;

class UserBillboardController extends Controller
{
    public function index(Request $request)
    {
        $rs['status'] = false;

        $validatedData = $request->validate([
            'openid' => 'required',  
                  
        ]);
        
        $where['openid'] = $request->openid;
        $list   = UserBillboard::where($where)
                                ->orderBy('id','desc')
                                ->paginate(10);
        
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function show(Request $request)
    {
    	$rs['status'] = false;

        $validatedData = $request->validate([           
            'id'    => 'required',      
        ]);
        
        $list = [];
        $ub   = UserBillboard::find($request->id);
        if(array_get($ub,'billboard_ids')) {
            $ids = explode(',',$ub->billboard_ids);
            $list = Billboard::whereIn('id',$ids)->get();    
        }
        
    	$rs['data'] = $list;
    	return response()->json($rs);
    }

    

    public function save(Request $request)
    {
        $rs['status'] = false;
        $data = $request->all();        
        $data = UserBillboard::create($data);
        if($data) {
            $rs['status'] = true;            
            $rs['data'] = $data;           
            return response()->json($rs);
        }
       
        return response()->json($rs);
        
    }

    public function update(Request $request)
    {
        $rs['status'] = false;
        $data = $request->all();        
        $data = UserBillboard::where(['id'=>$data['id']])->update($data);
        if($data) {
            $rs['status'] = true;            
            $rs['data'] = $data;           
            return response()->json($rs);
        }
       
        return response()->json($rs);
        
    }

    public function del(Request $request)
    {
        $rs['status'] = false;
        $data = $request->all();
        $where['id']   = (int)$request->id;
        $where['openid'] = $request->openid;
        $data = UserBillboard::where($where)->delete();
        if($data) {
            $rs['status'] = true;            
            $rs['data'] = $data;           
            return response()->json($rs);
        }
       
        return response()->json($rs);
        
    }
}
